package edu.whu.xterm.activity;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;
import edu.whu.xterm.Board;
import edu.whu.xterm.R;
import edu.whu.xterm.XApplication;
import edu.whu.xterm.db.XTerm.FavoriteColumns;
import edu.whu.xterm.http.RequestBuilder;
import edu.whu.xterm.util.Constants;
import edu.whu.xterm.util.SharedPrefManager;
import edu.whu.xterm.widget.OnRefreshListener;
import greendroid.widget.GActionBar;
import greendroid.widget.LoaderActionBarItem;

public class FavoriteActivity extends LoadingActivity implements
		OnRefreshListener<LoaderActionBarItem>, AdapterView.OnItemClickListener {

	static final int FAVORITE_CURSOR_LOADER = 0x01;

	static final Pattern PATTERN = Pattern.compile("(?<=BoardS\\().{1,200}?(?=\\);)");

	private static final String[] PROJECTION = { FavoriteColumns._ID, FavoriteColumns.BID,
			FavoriteColumns.DESC, FavoriteColumns.NAME, FavoriteColumns.IS_GROUP };

	private static final String[] FROM = { FavoriteColumns.DESC, FavoriteColumns.NAME };

	private static final int[] TO = { R.id.board_desc, R.id.board_name };

	private GActionBar actionBar;

	LoaderActionBarItem loaderItem;

	private ListView target;

	List<Board> favoritedBoards;

	List<Map<String, String>> mDataMap;

	volatile boolean loading = false;

	BaseAdapter adapter;

	public FavoriteActivity() {
		mDataMap = new ArrayList<Map<String, String>>();
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_loading_list_view);
		actionBar = ((MainTabActivity) getParent()).getGActionBar();
		loaderItem = (LoaderActionBarItem) actionBar.getItem(MainTabActivity.ITEM_REFRESH);
		target = (ListView) findViewById(android.R.id.list);
		target.setOnItemClickListener(this);
		initLoadingView(target);
		boolean localInited = getXApplication().getSharedPrefManager().readBoolean(
				SharedPrefManager.FAVORITE_SAVED);
		if (localInited) {
			Cursor cursor = getContentResolver().query(FavoriteColumns.CONTENT_URI, PROJECTION,
					null, null, null);
			adapter = new SimpleCursorAdapter(getApplicationContext(), R.layout.favorite_list_item,
					cursor, FROM, TO);
			target.setAdapter(adapter);
			loadSuccessed();
		} else {
			adapter = new SimpleAdapter(getApplicationContext(), mDataMap,
					R.layout.favorite_list_item, FROM, TO);
			target.setAdapter(adapter);

			executeLoadTask();
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
		actionBar.setTitle(getString(R.string.tab_favorite_title));
	}

	@Override
	public synchronized void executeLoadTask() {
		XApplication xapp = (XApplication) getApplication();
		if (xapp.isLogined()) {
			if (!loading) {
				new FavoriteAsyncTask().execute();
				loading = true;
			}
		} else if (xapp.getSharedPrefManager().readBoolean(SharedPrefManager.AUTO_LOGIN)) {
			startActivity(new Intent(xapp, LoginActivity.class));
		}else{
			//TODO 
		}
	}

	@Override
	public void onRefresh(LoaderActionBarItem t) {
		if (loading) {
			t.setLoading(false);
			return;
		}
		executeLoadTask();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode != KeyEvent.KEYCODE_BACK) {
			return super.onKeyDown(keyCode, event);
		}
		return false;
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		Board board;
		if (favoritedBoards != null) {
			board = favoritedBoards.get(position);
		} else {
			Cursor cursor = (Cursor) adapter.getItem(position);
			board = new Board();
			board.bid = cursor.getInt(1);
			board.desc = cursor.getString(2);
			board.name = cursor.getString(3);
			board.isGroup = cursor.getInt(4) == 1;
		}
		if (board.isGroup) {
			Toast.makeText(getApplicationContext(), R.string.not_supported_yet, Toast.LENGTH_SHORT)
					.show();
			return;
		}
		Intent intent = new Intent(getApplicationContext(), BoardArticleListActivity.class);
		intent.putExtra(BoardArticleListActivity.KEY_BOARD_NAME, board.name);
		intent.putExtra(BoardArticleListActivity.KEY_BOARD_DESC, board.desc);
		startActivity(intent);
	}

	private class FavoriteAsyncTask extends AsyncTask<Void, Void, Boolean> {

		@Override
		protected void onPreExecute() {
			loaderItem.setLoading(true);
		}

		@Override
		protected Boolean doInBackground(Void... params) {
			try {
				InputStream is = RequestBuilder.getBuilder()
						.loginPageRequest(Constants.SITE + Constants.PATH_FAVORITE_BOARD).call();
				Document document = Jsoup.parse(is, "gb2312", Constants.SITE);
				Elements boardElements = document
						.select("table.TableBorder1 script[language=JavaScript]");
				if (!boardElements.isEmpty() && boardElements.size() == 2) {
					Element boardElement = boardElements.get(0);
					String text = boardElement.html();
					Matcher matcher = PATTERN.matcher(text);
					favoritedBoards = new ArrayList<Board>();
					List<ContentValues> cvList = new ArrayList<ContentValues>();
					while (matcher.find()) {
						String tmp = matcher.group();
						Board board = new Board();
						StringTokenizer st = new StringTokenizer(tmp, "','");
						board.isGroup = Integer.valueOf(st.nextToken()) == 1;
						board.isFavGroup = Integer.valueOf(st.nextToken()) == 1;
						board.name = st.nextToken();
						board.desc = st.nextToken();
						st.nextToken();
						// board.todayNum = Integer.valueOf(st.nextToken());
						board.articleNum = Integer.valueOf(st.nextToken());
						board.position = Integer.valueOf(st.nextToken());
						board.bid = Integer.valueOf(st.nextToken());
						// board.onlineNum = Integer.valueOf(st.nextToken());
						favoritedBoards.add(board);

						Map<String, String> data = new HashMap<String, String>();
						data.put(FROM[0], board.desc);
						data.put(FROM[1], board.name);
						// data.put(FROM[2], "");
						mDataMap.add(data);
						ContentValues cv = new ContentValues();
						cv.put(FavoriteColumns.IS_GROUP, board.isGroup ? 1 : 0);
						cv.put(FavoriteColumns.IS_FAV_GROUP, board.isFavGroup ? 1 : 0);
						cv.put(FavoriteColumns.NAME, board.name);
						cv.put(FavoriteColumns.DESC, board.desc);
						cv.put(FavoriteColumns.ARTICLE_NUM, board.articleNum);
						cv.put(FavoriteColumns.POSITION, board.position);
						cv.put(FavoriteColumns.BID, board.bid);
						cvList.add(cv);
					}
					getContentResolver().bulkInsert(FavoriteColumns.CONTENT_URI,
							cvList.toArray(new ContentValues[] {}));
					getXApplication().getSharedPrefManager().writePref(
							SharedPrefManager.FAVORITE_SAVED, true);
				}
			} catch (Exception e) {
				e.printStackTrace();
				return Boolean.FALSE;
			}
			return Boolean.TRUE;
		}

		@Override
		protected void onPostExecute(Boolean result) {
			loaderItem.setLoading(false);
			loading = false;
			if (result.booleanValue()) {
				adapter.notifyDataSetChanged();
				loadSuccessed();
			} else if (adapter.isEmpty()) {
				loadFailed();
			} else {
				loadSuccessed();
			}
		}
	}
}